package com.agile.leetcode.redis.redisson.lockwithtime;

import com.agile.leetcode.redis.redisson.config.RedissionConfig;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @Author KD
 * @Date 2021/1/22 13:52
 */
public class LockWithTime {
    public static void main(String[] args) throws InterruptedException {
        LockWithTime lockWithTime = new LockWithTime();
        lockWithTime.lockWithTime("czk", 1, 1);
    }

    /**
     * @param resource  锁资源
     * @param waitTime  等待时间
     * @param leaseTime
     */
    public void lockWithTime(String resource, int waitTime, int leaseTime) throws InterruptedException {
        // 拿到客户端
        RedissonClient redissonClient = RedissionConfig.getRedissonClient();
        // 创建锁
        RLock lock = redissonClient.getLock(resource);
        // 第一个线程去获取锁
        new Thread(() -> {
            try {
                // 锁住
                lock.lock();
                // 业务处理
                handler();
            } finally {
                // 释放锁
                lock.unlock();
            }
        }).start();
        TimeUnit.SECONDS.sleep(1);
        // 另外一个线程去带超时时间获取
        new Thread(() -> {
            try {
                boolean b = lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
                if (b) {
                    try {
                        System.out.println(Thread.currentThread().getName() + "获取到锁了");
                    } finally {
                        lock.unlock();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName() + "超时了，在" + waitTime + "内没有获取到锁");
                }
            } catch (InterruptedException e) {

            }
        }).start();
    }

    /**
     * 业务处理
     */
    private void handler() {
        System.out.println(Thread.currentThread().getName() + "获取到锁了");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
